package org.msfj.authority.client.interceptor;

import org.msfj.authority.client.config.ClientAuthConfig;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.msfj.common.annotation.Constants;
import org.msfj.common.context.UserContextHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 设置feign请求的头部token
 */
public class ClientFeignRequestInterceptor implements RequestInterceptor {
    private Logger logger = LoggerFactory.getLogger(ClientFeignRequestInterceptor.class);
    @Autowired
    private ClientAuthConfig clientAuthConfig;

    @Override
    public void apply(RequestTemplate requestTemplate) {
        try {
            logger.trace("设置header[" + clientAuthConfig.getTokenHeader() + "]:" + clientAuthConfig.getName() + ";" + clientAuthConfig.getSecret());
            requestTemplate.header(clientAuthConfig.getTokenHeader(), clientAuthConfig.getName() + ";" + clientAuthConfig.getSecret());
            requestTemplate.header(Constants.CONTEXT_KEY_USER_ID, UserContextHandler.getUserID());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("设置头部token错误", e);
        }
    }
}
